package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.config.CustException;
import com.heima.common.exception.config.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.NewsAuthDto;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.media.vos.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.model.media.pojos.WmNews;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    WmMaterialMapper wmMaterialMapper;
    @Autowired
    KafkaTemplate kafkaTemplate;
    @Autowired
    WmNewsMapper wmNewsMapper;
    @Autowired
    WmUserMapper wmUserMapper;
    /**
     * 分页带条件查询自媒体文章列表<
     *
     * @param dto
     * @return
     */
    @Value("${file.oss.web-site}")
    private String website;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.构建条件，执行查询
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getBeginPubdate() != null || dto.getEndPubdate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //当前自媒体人用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);//不存在
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        wrapper.orderByDesc(WmNews::getCreatedTime);
        IPage<WmNews> ipage = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> page = page(ipage, wrapper);
        //3.封装数据，返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        pageResponseResult.setHost(website);
        return pageResponseResult;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVoById(Integer id) {
        //1.参数校验
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询
        //文章内容
        WmNews wmNews = super.getById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        //作者
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmUserMapper.selectById(userId);
        if (wmUser!=null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        //3.封装结果返回
        ResponseResult result = ResponseResult.okResult(wmNewsVo);
        result.setHost(website);
        return result;
    }

    /**
     * 查询内容审核列表
     *
     * @param newsAuthDto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDto newsAuthDto) {
        //1.参数校验
        if (newsAuthDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        newsAuthDto.checkParam();
        //2.执行查询
        //title
        if (StringUtils.isNotBlank(newsAuthDto.getTitle())){
            newsAuthDto.setTitle("%"+newsAuthDto.getTitle()+"%");
        }
        //分页 page,szie
        Integer page = newsAuthDto.getPage();
        newsAuthDto.setPage((page-1)*newsAuthDto.getSize());
        //查询
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(newsAuthDto);
        long listCount = wmNewsMapper.findListCount(newsAuthDto);
        //封装结果返回
        PageResponseResult result = new PageResponseResult(page, newsAuthDto.getSize(), listCount, listAndPage);
        result.setHost(website);

        return result;
    }

    /**
     * 查询需要发布文章的id列表
     * status=4 ，8,发布时间<=当前时间
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        //查询条件 获取status=4 ，8,发布时间<=当前时间文章的id
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery().in(WmNews::getStatus, WmNews.Status.ADMIN_SUCCESS.getCode(), WmNews.Status.SUCCESS.getCode())
                .le(WmNews::getPublishTime, new Date())
                .select(WmNews::getId);
        List<WmNews> list = super.list(wrapper);
        List<Integer> idList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        //返回结果
        return idList;
    }

    /**
     * 自媒体文章-发布、修改、保存草稿
     *
     * @param wmNewsDto
     * @param isSubmit  1为提交，0为草稿
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto, Short isSubmit) {
        //1.参数校验
        if (wmNewsDto == null || StringUtils.isBlank(wmNewsDto.getContent())) {
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //2.1假设文章布局为自动，需要先把type设为null
        if (wmNewsDto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            wmNews.setType(null);
        }
        //2.2封装图片
        String images = imagesList(wmNewsDto.getImages(), website);
        wmNews.setImages(images);
        //2.3保存或修改
        saveWmNews(wmNews);
        //3保存文章内容和素材的关系
        //3.1从文章内容解析图片列表
        List<Map<String, String>> contents = JSONObject.parseObject(wmNewsDto.getContent(), List.class);
        //3.2获取内容中的图片，无前缀webSite
        List<String> materials = parseContentImages(contents);
        //3.3保存文章内容和素材的关系
        if (isSubmit.intValue() == WmNews.Status.SUBMIT.getCode() && materials.size() > 0) {
            saveRelativeInfoForContent(materials, wmNews.getId());
        }
        //4保存文章封面和素材的关系
        if (isSubmit.intValue() == WmNews.Status.SUBMIT.getCode()) {
            saveRelativeInfoForCover(wmNewsDto, materials, wmNews);
        }
        //5.发消息给admin审核文章
        if (isSubmit.intValue()==WmNews.Status.SUBMIT.getCode()){
            Map<String, Integer> map=new HashMap<>();
            map.put(NewsAutoScanConstants.WM_NEWS_ID,wmNews.getId());
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(map));
        }
        //6.返回结果
        return ResponseResult.okResult();
    }


    /**
     * 把images封面集合转化为字符串,并去除前缀webSite
     *
     * @param images
     * @param website
     * @return
     */
    private String imagesList(List<String> images, String website) {
        if (images.size() > 0) {
            return images.stream().map((url) -> url.replace(website, "").replace(" ", ""))
                    .collect(Collectors.joining(","));
        }
        return null;
    }


    /**
     * 封装方法保存或修改
     *
     * @param wmNews
     */
    private void saveWmNews(WmNews wmNews) {
        if (wmNews.getId() == null) {
            wmNews.setCreatedTime(new Date());
            wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
            wmNews.setSubmitedTime(new Date());
            wmNews.setEnable(WemediaConstants.WM_NEWS_UPENABLE);//上架
            super.save(wmNews);//id为空保存
        } else {//修改并且删除文章和素材中间表相关的数据
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            wmNews.setSubmitedTime(new Date());
            super.updateById(wmNews);

        }
    }

    /**
     * 解析文章内容中的图片列表，去除前缀
     *
     * @param contents
     * @return
     */
    private List<String> parseContentImages(List<Map<String, String>> contents) {
        return contents.stream()
                .filter(map -> map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) //过滤type=image的集合
                .map(x -> x.get("value"))//获取到image下的value图片url
                .map(url -> url.replace(website, "").replace(" ", ""))//去除前缀
                .collect(Collectors.toList());//转成list集合
    }

    /**
     * 保存文章内容中内容图片和素材的关系
     *
     * @param materials
     * @param wmNewsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer wmNewsId) {
        saveRelativeInfo(materials, wmNewsId, WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 人工审核文章，通过4和驳回2
     *
     * @param newsAuthDto
     * @param status
     * @return
     */
    @Override
    public ResponseResult updateStatus(NewsAuthDto newsAuthDto,Integer status) {
        //1.参数校验
        if (newsAuthDto==null||newsAuthDto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.审核文章 先查后改
        WmNews wmNews = getById(newsAuthDto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNews.setStatus( status);
        if (StringUtils.isNotBlank(newsAuthDto.getMsg())){
            wmNews.setReason(newsAuthDto.getMsg());
        }
        updateById(wmNews);
        //返回结果
        return ResponseResult.okResult();
    }

    /**
     * 文章上下架操作
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        //1.参数校验
        if (wmNewsDto == null || wmNewsDto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上下架业务执行
        WmNews wmNews = super.getById(wmNewsDto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //查询文章是否发布
        if (wmNews.getStatus()!=(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章未发布，不能下架");
        }
        if (wmNewsDto.getEnable() > -1 && wmNewsDto.getEnable() < 2) {
            //  wmNews.setEnable(dto.getEnable() == 1 ? true : false);
            //  updateById(wmNews);

            update(Wrappers.<WmNews>lambdaUpdate()
                    .eq(WmNews::getId, wmNews.getId())
                    .set(WmNews::getEnable, wmNewsDto.getEnable()));

        }
        // TODO 同步APP端文章显示
        //发送消息
        if (wmNews.getArticleId()!=null){
            HashMap<String,Object> map = new HashMap<>();
            map.put("enable",wmNewsDto.getEnable());
            map.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
        }

        //3.返回结果
        return ResponseResult.okResult();
    }

    /**
     * 根据id删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNewsById(Integer id) {
        //1.参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.删除业务执行
        //查询当前id文章是否存在
        WmNews wmNews = super.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询当前文章状态，上架时无法删除
        Integer status = wmNews.getStatus();
        if (status==WmNews.Status.PUBLISHED.getCode() && wmNews.getEnable()==(WemediaConstants.WM_NEWS_UPENABLE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "文章已发布，不能删除");
        }
        //删除文章
        super.removeById(id);
        //删除关系表的数据
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
        wmNewsMaterialMapper.delete(wrapper);
        //3.返回结果

        return ResponseResult.okResult();
    }

    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1.参数校验4
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询业务执行
        WmNews wmNews = super.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.返回结果

        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(website);
        return responseResult;
    }

    /**
     * 执行保存文章和素材的关系
     *
     * @param materials
     * @param wmNewsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer wmNewsId, Short type) {
        //1.根据图片url查询素材的id列表
        List<WmMaterial> dbmaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, materials)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        //bug:保存之前先查询，草稿中的内容如果取不到素材对应的id，则直接抛出异常，停止保存关系
        //2.校验素材列表


        System.out.println(dbmaterials);
        if (dbmaterials == null || dbmaterials.size() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Map<String, Integer> matreialMap = dbmaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        List<Integer> materialIds = new ArrayList<>();
        for (String url : materials) {
            Integer id = matreialMap.get(url);
            if (id == null) {
                CustException.cust("图片素材已被删除，请重新上传");
            }
            materialIds.add(id);
        }
        //3.执行保存到数据库 wm_news_matreial
        wmNewsMaterialMapper.saveRelations(materialIds, wmNewsId, type);
    }

    /**
     * 保存文章封面和素材的关系
     *
     * @param wmNewsDto
     * @param materials
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, List<String> materials, WmNews wmNews) {
        //1.取出前端封面集合
        List<String> images = wmNewsDto.getImages();
        //2.文章布局为自动，type=-1,从内容中取出图片保存到数据库
        if (wmNewsDto.getType().intValue() == WemediaConstants.WM_NEWS_TYPE_AUTO.intValue()) {
            int size = materials.size();
            if (size > 0 && size < 3) {
                images = materials.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE.intValue());//type=1，单图
            }
            if (size >= 3) {
                images = materials.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE.intValue());//type=3,多图
            }
            if (size == 0) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE.intValue());//无图
            }
            //修改数据
            if (images != null && images.size() > 0) {
                String url = imagesList(images, website);
                wmNews.setImages(url);
                super.updateById(wmNews);
            }
        }
    }

}
